/*
 * @Author: linyi
 * @Date: 2018-11-19 10:51:13
 * @Last Modified by: linyi
 * @Last Modified time: 2019-03-18 11:18:27
 */
import React, { Component } from 'react'
import moment from 'moment'
import { request } from 'Utils'
import { message } from 'antd'
import { order as OrderApi, orderCenter as OrderCenter } from 'ApiMapper'
import { Form, Table } from './components'
import { connect } from 'react-redux'
import { actions } from '@/layout/index'

const { API_POST_REFUND_ORDERS_LIST } = OrderCenter
const { ORDER_STATUS } = OrderApi

class App extends Component {
  constructor() {
    super()

    this.state = {
      dataSource: [], // 数据
      pageIndex: 1, // 当前页
      totalPage: 0, // 总条数
      pageSize: 50, // 每页条数
      searchParams: {}, // 查询条件
      tableLoading: false, // 表格 loading
      selectedRowKeys: [], // 表格中选中的数据集下标
      selectedRows: [], // 表格中选中的数据集
      isSelectAll: false, // 是否全选

      type: '', // 弹出框标志位
      record: {}, // 记录
      orderStatusLoading: false,
      orderStatusChoices: [],
      orderStatusMap: new Map(),
    }
  }

  async componentDidMount() {
    this.props.changeBreadcrumb(['订单中心', '退货列表'])

    this.setState({ orderStatusLoading: false })
    await request(ORDER_STATUS, 'GET')
      .then(({ result }) => {
        const orderStatusChoices = result.map(({ code, value }) => ({
          value: code,
          label: value,
        }))
        const orderStatusMap = new Map(
          orderStatusChoices.map(({ value, label }) => [
            value.toString(),
            label,
          ]),
        )
        this.setState({ orderStatusChoices, orderStatusMap })
      })
      .finally(() => this.setState({ orderStatusLoading: false }))

    this.fetchRequestData({})
  }

  /* ---------- 数据交互操作 ---------- */
  fetchRequestData = searchParams => {
    if (!searchParams) return

    Object.keys(searchParams).forEach(key => {
      const element = searchParams[key]
      if (element === '') delete searchParams[key]
    })
    searchParams = {
      ...searchParams,
      pageNo: this.state.pageIndex,
      pageSize: this.state.pageSize,
    }
    this.setState({ tableLoading: true })
    request(API_POST_REFUND_ORDERS_LIST, 'POST', { data: searchParams }).then(
      result => {
        if (result && result.page && result.page.result) {
          const { orderStatusMap } = this.state
          this.setState({
            dataSource: result.page.result.map((item, index) => ({
              ...item,
              createdTime: item.createdTime
                ? moment(item.createdTime).format('YYYY/MM/DD HH:mm:ss')
                : '--',
              updatedTime: item.updatedTime
                ? moment(item.updatedTime).format('YYYY/MM/DD HH:mm:ss')
                : '--',
              orderStatus:
                orderStatusMap.get(item.orderStatus.toString()) || '--',
              key: index,
            })),
            totalPage: result.page.totalNum,
          })
        }

        this.resetSelectedRowKeys()
      },
    ).finally(() => this.setState({ tableLoading: false }))
  }

  handlePageSizeChange = (pageIndex, pageSize) => {
    if (!pageIndex || !pageSize) return
    this.setState({ pageIndex, pageSize }, () => this.fetchRequestData(this.state.searchParams))
  }

  handleSearchParams = searchParams => {
    console.info(searchParams)
    if (!searchParams) return
    this.setState({ pageIndex: 1, searchParams }, () => this.fetchRequestData(this.state.searchParams))
  }

  refreshTable = () => {
    this.fetchRequestData(this.state.searchParams)
  }
  /* ---------- 数据交互操作 ---------- */

  /* ---------- 表格操作 ---------- */
  resetSelectedRowKeys = () => {
    this.setState({ selectedRowKeys: [], selectedRows: [] })
  }

  handleSelectChange = (selectedRowKeys, selectedRows) => {
    this.isSelectAll = selectedRows.length && selectedRows.length >= this.state.dataSource.length
    this.setState({ selectedRowKeys, selectedRows })
  }

  updateSelectedRows = (record, selected, selectedRows) => {
    if (!selectedRows) return
    this.handleSelectChange(selectedRows.map(item => item.key), selectedRows)
  }
  /* ---------- 表格操作 ---------- */

  /* --------- 弹出框或跳转页面 ---------- */
  /* 跳转 新增 */
  // showAddPage = () => history.push('/marketing/promotionCenter/add')

  /* 取消 弹框 */
  handleCancel = () => this.setState({ type: '' })

  /* 增加 弹框 */
  showAddPopUp = () => this.setState({ type: '1' })

  /* 修改 弹框 */
  showEditPopUp = record => {
    if (record) this.setState({ record })
  }

  /* 删除 弹框 */
  showDeletePopUp = () => {
    if (!this.state.selectedRows.length) return message.error('至少选择一项')
    return this.setState({ type: '3' })
  }

  /* --------- 弹出框 ---------- */

  /* --------- 常用操作 ---------- */

  /* --------- 常用操作 ---------- */

  render() {
    const {
      tableLoading,
      dataSource,
      pageIndex,
      totalPage,
      pageSize,
      selectedRowKeys,
      selectedRows,
      record,
      isSelectAll,
      orderStatusLoading,
      orderStatusChoices,
    } = this.state
    return (
      <section>
        <Form
          orderStatusChoicesLoading={orderStatusLoading}
          orderStatusChoices={orderStatusChoices}
          handleSearchParams={this.handleSearchParams}
        />
        <Table
          dataSource={dataSource}
          pageIndex={pageIndex}
          totalPage={totalPage}
          pageSize={pageSize}
          handlePageSizeChange={this.handlePageSizeChange}
          tableLoading={tableLoading}
          selectedRowKeys={selectedRowKeys}
          selectedRows={selectedRows}
          isSelectAll={isSelectAll}
          handleSelectChange={this.handleSelectChange}
          updateSelectedRows={this.updateSelectedRows}
          refreshTable={this.refreshTable}
          showEditPopUp={this.showEditPopUp}
          handleDisable={this.handleDisable}
          handleDelete={this.handleDelete}
          record={record}
        />
        {this.state.type && this.switchType(this.state.type)}
      </section>
    )
  }
}

export default connect(
  () => ({}),
  {
    changeBreadcrumb: actions.changeBreadcrumb,
  },
)(App)
